<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author FIRE
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="false"
    :okAuth="'shop:order:cusFpApply:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="70%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>

    <Tabs v-model:activeKey="activeKey" tabPosition="left">
      <Tabs.TabPane key="1" :forceRender="true" tab="基本信息">
        <BasicForm @register="registerForm">
          <template #cusFpApplyRdsList>
            <BasicTable
              @register="registerCusFpApplyRdsTable"
              @row-click="handleCusFpApplyRdsRowClick"
            />
            <!-- <a-button class="mt-2" @click="handleCusFpApplyRdsAdd" v-auth="'shop:order:cusFpApply:edit'">
              <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
            </a-button> -->
          </template>
          <template #listDetails>
            <div style="display: flex; justify-content: center">
              <!-- type="primary" -->
              <a-button class="mt-2" @click="handleListDetails">
                <Icon icon="ant-design:eye-outlined" /> {{ t('查看订单详情') }}
              </a-button>
            </div>
          </template>
        </BasicForm>
      </Tabs.TabPane>

      <Tabs.TabPane key="2" :forceRender="true" tab="开票信息">
        <BasicForm @register="registerForm1"> </BasicForm>
      </Tabs.TabPane>

      <!-- <Tabs.TabPane key="3" :forceRender="true" tab="表单栏目">
        <FormCol :colpop="colpop" />
      </Tabs.TabPane>

      <Tabs.TabPane key="4" :forceRender="true" tab="表单按钮">
        <FormBtn :colpop="colpop" />
      </Tabs.TabPane> -->
      <!-- 订单详情 -->
    </Tabs>
    <ListDetails @register="registerDrawerListDetails" />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsShopOrderCusFpApplyForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner, useDrawer } from '/@/components/Drawer';
  import { CusFpApply, cusFpApplySave, cusFpApplyForm } from '/@/api/shop/order/cusFpApply';
  import { Tabs } from 'ant-design-vue';
  import ListDetails from './listDetails.vue';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('shop.order.cusFpApply');
  const { showMessage } = useMessage();
  const record = ref<CusFpApply>({} as CusFpApply);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增开票申请') : t('查看开票申请'),
  }));
  const activeKey = ref<string>('1');

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('客户编码'),
      field: 'cusCode',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('客户名称'),
      field: 'basCus.name',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('申请人'),
      field: 'creator.userName',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('申请时间'),
      field: 'createDate',
      component: 'DatePicker',
      dynamicDisabled: true,
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
    },
    {
      label: t('开票人'),
      field: 'overBy',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
    },
    {
      label: t('开票完成'),
      field: 'overDate',
      component: 'DatePicker',
      dynamicDisabled: true,
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
    },
    {
      label: t('申请金额'),
      field: 'isum',
      component: 'Input',
      dynamicDisabled: true,
      defaultValue: '0.00',
      componentProps: {
        maxlength: 16,
      },
      // rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('开票状态'),
      field: 'kpStatus',
      component: 'Select',
      dynamicDisabled: true,
      componentProps: {
        dictType: 'cus_fp_status',
        allowClear: true,
      },
      // required: true,
    },
    {
      label: t('申请附件'),
      field: 'dataMap',
      component: 'Upload',
      dynamicDisabled: true,
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'cusFpApply_image',
        uploadType: 'image',
      },
      colProps: { lg: 24, md: 24 },
      // 文件上传的必填验证实例
      // rules: [
      //   { required: true },
      //   {
      //     validator(_rule, value) {
      //       return new Promise((resolve, reject) => {
      //         const len = !value || value['testData_image__len'] || 0;
      //         if (len == 0) reject(t('请上传图片'));
      //         else resolve();
      //       });
      //     },
      //   },
      // ],
    },
    {
      label: t('发票附件'),
      field: 'dataMap',
      component: 'Upload',
      dynamicDisabled: true,
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'cusFpApply_file',
        uploadType: 'file',
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('发票链接'),
      field: 'fpUrl',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 1000,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('备注信息'),
      field: 'remarks',
      component: 'InputTextArea',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('取消原因'),
      field: 'cancleRemarks',
      component: 'InputTextArea',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      // label: t('查看订单详情'),
      field: 'listDetails',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'listDetails',
    },

    {
      label: t('申请明细'),
      field: 'cusFpApplyRdsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'cusFpApplyRdsList',
    },
  ];
  const inputFormSchemas1: FormSchema[] = [
    {
      label: t('抬头类型'),
      field: 'kpInfo.ctype',
      component: 'Select',
      dynamicDisabled: true,
      componentProps: {
        dictType: 'cus_fp_type',
        allowClear: true,
      },
    },

    {
      label: t('抬头名称'),
      field: 'kpInfo.cname',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
    },
    {
      label: t('发票税号'),
      field: 'kpInfo.dutyNo',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
    },

    {
      label: t('联系电话'),
      field: 'kpInfo.contactInfo',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
    },
    {
      label: t('开户银行'),
      field: 'kpInfo.bankName',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
    },

    {
      label: t('银行帐号'),
      field: 'kpInfo.bankCode',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
    },
    {
      label: t('单位号码'),
      field: 'kpInfo.dwNo',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
    },
    {
      label: t('单位地址'),
      field: 'kpInfo.dwAddr',
      component: 'Input',
      dynamicDisabled: true,
      componentProps: {
        maxlength: 64,
      },
    },
  ];

  const [registerDrawerListDetails, { openDrawer: openDrawerListDetails }] = useDrawer();
  const [registerForm, { resetFields, setFieldsValue, getFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });
  const [
    registerForm1,
    {
      resetFields: resetFields1,
      setFieldsValue: setFieldsValue1,
      getFieldsValue: getFieldsValue1,
      validate: validate1,
    },
  ] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas1,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerCusFpApplyRdsTable, cusFpApplyRdsTable] = useTable({
    // actionColumn: {
    //   width: 60,
    //   actions: (record: Recordable) => [
    //     {
    //       icon: 'ant-design:delete-outlined',
    //       color: 'error',
    //       popConfirm: {
    //         title: '是否确认删除',
    //         confirm: handleCusFpApplyRdsDelete.bind(this, record),
    //       },
    //       auth: 'shop:order:cusFpApply:edit',
    //     },
    //   ],
    // },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setCusFpApplyRdsTableData(_res: Recordable) {
    cusFpApplyRdsTable.setColumns([
      {
        title: t('订单号'),
        dataIndex: 'orderCode',
        width: 160,
        align: 'center',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 100,
        // },
        // editRule: true,
      },
      {
        title: t('订单日期'),
        dataIndex: 'soMain.ddate',
        width: 80,
        align: 'center',
      },
      {
        title: t('业务类型'),
        dataIndex: 'soMain.cbustype',
        width: 80,
        align: 'center',
      },
      {
        title: t('税率'),
        dataIndex: 'soMain.itaxrate',
        width: 80,
        align: 'center',
      },
      {
        title: t('金额'),
        dataIndex: 'isum',
        width: 80,
        align: 'center',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 16,
        // },
        // editRule: true,
      },
    ]);
    cusFpApplyRdsTable.setTableData(record.value.cusFpApplyRdsList || []);
  }

  function handleCusFpApplyRdsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleCusFpApplyRdsAdd() {
    cusFpApplyRdsTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleListDetails() {
    openDrawerListDetails(true, { id: record.value.id });
  }

  async function handleCusFpApplyRdsDelete(record: Recordable) {
    await cusFpApplyRdsTable.deleteTableDataRecord(record);
    // let arr = await cusFpApplyRdsTable.getDataSource();
    // let isums = 0
    // arr.forEach((item) => {
    //   isums += item.isum;
    // });
    // setFieldsValue({
    //   ...getFieldsValue(),
    //   isum: isums,
    // });
  }

  async function getCusFpApplyRdsList() {
    let cusFpApplyRdsListValid = true;
    let cusFpApplyRdsList: Recordable[] = [];
    for (const record of cusFpApplyRdsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        cusFpApplyRdsListValid = false;
      }
      cusFpApplyRdsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of cusFpApplyRdsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      cusFpApplyRdsList.push({
        ...record,
        status: '1',
      });
    }
    if (!cusFpApplyRdsListValid) {
      throw { errorFields: [{ name: ['cusFpApplyRdsList'] }] };
    }
    return cusFpApplyRdsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    await resetFields1();
    const res = await cusFpApplyForm(data);
    record.value = (res.cusFpApply || {}) as CusFpApply;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setFieldsValue1(record.value);
    setCusFpApplyRdsTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data1 = await validate();
      const data2 = await validate1();

      let data = {
        ...data1,
        ...data2,
      };

      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.cusFpApplyRdsList = await getCusFpApplyRdsList();
      // console.log('submit', params, data, record);
      const res = await cusFpApplySave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
